package com.nulldev.util.net.tcp.dynReader;

import java.util.concurrent.CopyOnWriteArrayList;

import com.nulldev.util.java.DataSet;
import com.nulldev.util.net.packets.NetInfoAdapter;
import com.nulldev.util.net.packets.NetPacket;
import com.nulldev.util.net.packets.PacketManager;
import com.nulldev.util.net.tcp.TCPCore;
import com.nulldev.util.net.tcp.server.TCPServer;

public class DTCPServer extends TCPServer {

	private final CopyOnWriteArrayList<DataSet<NetPacket, TCPCore>> packets = new CopyOnWriteArrayList<DataSet<NetPacket, TCPCore>>();
	public DTCPServer(String category, String name, int port) {
		super(category, name, port);
	}
	
	public DTCPServer(String category, String name, int port, final boolean open) {
		super(category, name, port, open);
	}


	@Override
	public void receive(TCPCore connection, String event, String payload, byte[] bytes, long length, final long readTime) {
		final NetPacket packet = PacketManager.parsePacket(this, connection, event, bytes);
		if (!packet.isGeneric()) {
			this.packets.add(new DataSet<NetPacket, TCPCore>(packet, connection));
		}
	}

	public DataSet<NetPacket, TCPCore> readPacket() {
		try {
			return this.packets.remove(0);
		}catch (Exception e) {
			return new DataSet<NetPacket, TCPCore>(null, null);
		}
	}
	
	public boolean hasPackets() {
		return !this.packets.isEmpty();
	}
	
	public void processPacket(final DataSet<NetPacket, TCPCore> packet) {
		packet.getA().server(packet.getA().getData(), packet.getA().toString(), NetInfoAdapter.create(packet.getB()));	
	}
}
